﻿using SpiderPlatform.Entity;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks.Schedulers;

namespace SpiderPlatform.Service
{
    public class FreshBrandService
    {
        public void doWork()
        {
            List<FrechProduct> all = new List<FrechProduct>();
            var brandList = GetBrand();
            Logger.Info($"共获得{brandList.Count}个品牌");
            foreach (var item in brandList)
            {
                Logger.Info($"处理{item.BrandName}");
                var cateProducts = GetProduct(item);
                Logger.Info($"处理{item.BrandName}完成===》{cateProducts.Count}个商品");
                all.AddRange(cateProducts);
            }
            Logger.Info($"全部拉取完成，共{all.Count}个商品");
            TaskFactory fac = new TaskFactory(new LimitedConcurrencyLevelTaskScheduler(20));
            List<Task> taskList = new List<Task>();
            foreach (var prd in all)
            {
                var task = fac.StartNew(() =>
                {
                    GetDetail(prd);
                    Logger.Info($"{prd.Name}===>详情完成");
                });
                taskList.Add(task);
            }
            Task.WaitAll(taskList.ToArray());
            Logger.Info($"开始导出");
            var data = new StringBuilder("sku,店家ID,店家名称,品名,副标题,规格,价格,会员价,单价,是否售罄,Tag,天天低价,优质,冷链包装,评价数,评分,月销量" + Environment.NewLine);
            foreach (var item in all)
            {
                data.AppendLine($"{item.SKU},{item.BrandID},{item.BrandName}{item.CateGoryName},{item.Name},{item.Title},{item.Summary},{item.Price}," +
                    $"{item.PlusPprice},{item.ValuePackPrice},{item.IsSellOut},{item.Tag},{item.IsLower},{item.IsGood},{item.IsCold}," +
                    $"{item.Reviews},{item.Star},{item.OrderCount}");
            }
            if (System.IO.File.Exists("freshBrand.csv"))
            {
                System.IO.File.Delete("freshBrand.csv");
            }
            System.IO.File.AppendAllText("freshBrand.csv", data.ToString());
            Logger.Info("导出完成");
        }

        private List<FreshBrandEntity> GetBrand()
        {
            List<FreshBrandEntity> brandList = new List<FreshBrandEntity>();
            HttpClient client = new HttpClient();          
            var res = client.GetAsync("https://www.freshgogo.com/interface/topicBrand/getPcBrandList?homearea_id=1").Result;
            var str = res.Content.ReadAsStringAsync().Result;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(str);
            if (result.status == 1)
            {
                foreach (var item in result.data.list)
                {
                    brandList.Add(new FreshBrandEntity
                    {
                        BrandID = item.id,
                        BrandName = item.name
                    });
                }
            }
            return brandList;
        }

        List<FrechProduct> GetProduct(FreshBrandEntity brand)
        {
            List<FrechProduct> productList = new List<FrechProduct>();
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"https://www.freshgogo.com/interface/topicBrand/getPcDetailList?id={brand.BrandID}&homearea_id=1").Result;
            var str = res.Content.ReadAsStringAsync().Result;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(str);
            if (result.status == 1)
            {
                foreach (var item in result.data[0].commoditys)
                {
                    var prd = new FrechProduct
                    {
                        SKU = item.id,
                        Name = item.name,
                        CateGoryName = brand.BrandName,
                        OrderCount = item.order_quantity,
                        IsSellOut = item.is_sell_out,
                        Price = item.price,
                        PlusPprice = item.plus_price,
                       // Star = item.star_avg,
                       // Reviews = item.comment_num,
                        Summary = item.summary,
                        Title = item.adv_str,
                        ValuePackPrice = item.value_pack_price,
                        Tag = item.labels.Count > 0 ? item.labels[0].name : "",
                        BrandID=brand.BrandID,
                        BrandName=brand.BrandName,
                        IsCold= item.is_cold_pack
                    };
                    productList.Add(prd);
                }
            }
            return productList;
        }

        FrechProduct GetDetail(FrechProduct prd)
        {
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"https://www.freshgogo.com/interface/Commodity?id={prd.SKU}&user_id=&homearea_id=1").Result;
            var str = res.Content.ReadAsStringAsync().Result;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(str);
            if (result.status == 1)
            {
                prd.OrderCount = result.data.month_sell_pre;
                prd.Star = result.data.star;
                prd.Reviews = result.data.comment_count;
            }
            return prd;
        }        
    }
}
